#!/bin/bash

# Root directory where the script will start searching for subdirectories
root_dir=$(pwd)

# Traverse the root directory and process images in each subdirectory
find "$root_dir" -type d | while read sub_dir; do
    # Skip if the directory doesn't contain jpg files
    if ls "$sub_dir"/*.jpg 1> /dev/null 2>&1; then
        echo "Processing images in: $sub_dir"

        n=4  # 2 rows × 2 columns = 4 images per page
        counter=0
        group=1
        files=()

        # Get the folder name for naming the PDF
        folder_name=$(basename "$sub_dir")

        # Get the first JPG file in the directory to check its dimensions
        first_img=$(ls "$sub_dir"/*.jpg | head -n 1)

        # Get the dimensions of the first image (width and height)
        dimensions=$(identify -format "%wx%h" "$first_img")
        width=$(echo $dimensions | cut -d'x' -f1)
        height=$(echo $dimensions | cut -d'x' -f2)

        # Determine the prefix based on the dimensions
        if ((height > width)); then
            prefix="1_"  # Vertical image (height > width)
        else
            prefix="2_"  # Horizontal image (width > height)
        fi
       # Loop through all JPG files in the current subdirectory
        for img in "$sub_dir"/*.jpg; do
            files+=("$img")
            ((counter++))

            if ((counter == n)); then
                montage "${files[@]}" -tile 2x2 -geometry +0+0 "group${group}.jpg"
                unset files
                counter=0
                ((group++))
            fi
        done

        # Process any remaining images (but only if there are more than 1 image)
        if ((counter > 1)); then
            montage "${files[@]}" -tile 2x2 -geometry +0+0 "group${group}.jpg"
        fi

        # Only create PDF if there are merged images
        if ls group*.jpg 1> /dev/null 2>&1; then
            magick -density 300 group*.jpg -quality 100 "${sub_dir}/${prefix}${folder_name}.pdf"
        fi

        # Clean up temporary PNG files
        rm group*.jpg
    else
        echo "No JPG files found in: $sub_dir"
    fi
done
